<template>
	<view class="page-container">
		<view class="page-header">
			<view class="header-left">
				<text class="page-title">患者档案管理</text>
				<text class="page-subtitle">管理所有患者档案信息</text>
			</view>
			<view class="header-right">
				<button class="btn btn-primary" @click="handleAdd"><text class="icon">+</text> 新增患者</button>
			</view>
		</view>
		<view class="filter-section">
			<view class="search-box">
				<input v-model="searchParams.keyword" type="text" placeholder="搜索患者姓名、手机号..." class="search-input" @confirm="handleSearch" />
				<button class="btn-search" @click="handleSearch">搜索</button>
				<button class="btn-reset" @click="handleReset">重置</button>
			</view>
			
			<view v-if="selectedIds.length > 0" class="batch-actions">
				<text class="batch-count">已选中 {{ selectedIds.length }} 项</text>
				<button class="btn btn-danger btn-small" @click="handleBatchDelete">删除选中</button>
				<button class="btn btn-default btn-small" @click="handleCancelSelect">取消选择</button>
			</view>
		</view>
		<view class="table-wrapper">
			<view v-if="loading" class="loading-state"><text class="loading-text">加载中...</text></view>
			<view v-else-if="dataList.length === 0" class="empty-state"><text class="empty-icon">📭</text><text class="empty-text">暂无患者数据</text><button class="btn btn-primary" @click="handleAdd">新增患者</button></view>
			<view v-else class="table-container">
				<view class="table-header">
					<view class="table-cell checkbox-cell">
						<checkbox-group @change="handleSelectAll">
							<label>
								<checkbox :checked="isSelectAll" value="all" />
							</label>
						</checkbox-group>
					</view>
					<view class="table-cell col-name">患者姓名</view>
					<view class="table-cell col-gender">性别</view>
					<view class="table-cell col-age">年龄</view>
					<view class="table-cell col-mobile">联系电话</view>
					<view class="table-cell col-blood">血型</view>
					<view class="table-cell col-emergency">紧急联系人</view>
					<view class="table-cell col-emergency-phone">紧急联系电话</view>
					<view class="table-cell col-allergies">过敏史</view>
					<view class="table-cell col-diseases">既往病史</view>
					<view class="table-cell col-actions">操作</view>
				</view>
				<view v-for="item in dataList" :key="item._id" class="table-row"
					:class="{ selected: selectedIds.includes(item._id) }">
					<view class="table-cell checkbox-cell" @click.stop>
						<checkbox-group @change="(e) => handleSelectItem(item._id, e)">
							<label>
								<checkbox :checked="selectedIds.includes(item._id)" :value="item._id" />
							</label>
						</checkbox-group>
					</view>
					<view class="table-cell col-name clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.patient_name || '暂无' }}</text></view>
					<view class="table-cell col-gender clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.gender_text || '-' }}</text></view>
					<view class="table-cell col-age clickable" @click="handleView(item._id)"><text class="cell-text">{{ calculateAge(item.birth_date) }}</text></view>
					<view class="table-cell col-mobile clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.mobile || '-' }}</text></view>
					<view class="table-cell col-blood clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.blood_type || '-' }}</text></view>
					<view class="table-cell col-emergency clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.emergency_contact || '-' }}</text></view>
					<view class="table-cell col-emergency-phone clickable" @click="handleView(item._id)"><text class="cell-text">{{ item.emergency_phone || '-' }}</text></view>
					<view class="table-cell col-allergies clickable" @click="handleView(item._id)"><text class="cell-text text-truncate" :title="formatArray(item.allergies)">{{ formatArray(item.allergies) }}</text></view>
					<view class="table-cell col-diseases clickable" @click="handleView(item._id)"><text class="cell-text text-truncate" :title="formatArray(item.chronic_diseases)">{{ formatArray(item.chronic_diseases) }}</text></view>
					<view class="table-cell col-actions" @click.stop>
						<button class="action-btn edit-btn" @click="handleEdit(item._id)">编辑</button>
						<button class="action-btn delete-btn" @click="handleDelete(item._id)">删除</button>
					</view>
				</view>
			</view>
		</view>
		<view v-if="dataList.length > 0" class="pagination-section">
			<view class="pagination-info"><text>共 {{ total }} 条数据，第 {{ currentPage }} / {{ totalPages }} 页</text>
				<view class="page-size-selector"><text class="selector-label">每页显示</text><picker mode="selector" :range="pageSizeOptions" :value="pageSizeIndex" @change="handlePageSizeChange" class="selector-picker"><view class="selector-input">{{ pageSize }} 条</view></picker></view>
			</view>
			<view class="pagination-controls">
				<button :disabled="currentPage === 1" class="btn btn-default btn-small" @click="handlePreviousPage">上一页</button>
				<button :disabled="currentPage === totalPages" class="btn btn-default btn-small" @click="handleNextPage">下一页</button>
			</view>
		</view>
	</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
const dataList = ref([]), loading = ref(false), total = ref(0), currentPage = ref(1), pageSize = ref(20)
const pageSizeOptions = ['10 条', '20 条', '50 条', '100 条'], pageSizeValues = [10, 20, 50, 100]
const pageSizeIndex = computed(() => pageSizeValues.indexOf(pageSize.value))
const searchParams = ref({ keyword: '' })
const selectedIds = ref([])
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const isSelectAll = computed(() => dataList.value.length > 0 && dataList.value.length === selectedIds.value.length)
onMounted(() => { loadData() })

function calculateAge(birthDate) {
	if (!birthDate) return '-'
	const birth = new Date(birthDate)
	const today = new Date()
	let age = today.getFullYear() - birth.getFullYear()
	const monthDiff = today.getMonth() - birth.getMonth()
	if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
		age--
	}
	return age >= 0 ? `${age}岁` : '-'
}

function formatArray(arr) {
	if (!arr || !Array.isArray(arr) || arr.length === 0) return '无'
	return arr.join('、')
}

async function loadData() {
	loading.value = true
	try {
		const dhPatients = uniCloud.importObject('dh-patients')
		const skip = (currentPage.value - 1) * pageSize.value
		let query = {}
		if (searchParams.value.keyword) {
			query.keyword = searchParams.value.keyword
		}
		const result = await dhPatients.listPatients(query, skip, pageSize.value)
		if (result.code === 200) {
			dataList.value = result.data || []
			total.value = result.count || 0
			selectedIds.value = []
		} else { uni.showToast({ title: result.message || '加载失败', icon: 'error' }) }
	} catch (error) {
		console.error('加载数据失败:', error)
		uni.showToast({ title: '加载数据失败', icon: 'error' })
	} finally { loading.value = false }
}
function handleSearch() { currentPage.value = 1; loadData() }
function handleReset() { searchParams.value.keyword = ''; currentPage.value = 1; loadData() }
// 全选/取消全选
function handleSelectAll(e) {
	const values = e.detail.value
	if (values.includes('all')) {
		selectedIds.value = dataList.value.map(item => item._id)
	} else {
		selectedIds.value = []
	}
}

// 单个选择/取消选择
function handleSelectItem(id, e) {
	const values = e.detail.value
	if (values.includes(id)) {
		if (!selectedIds.value.includes(id)) {
			selectedIds.value.push(id)
		}
	} else {
		const index = selectedIds.value.indexOf(id)
		if (index > -1) {
			selectedIds.value.splice(index, 1)
		}
	}
}

// 取消选择
function handleCancelSelect() {
	selectedIds.value = []
}

// 批量删除
async function handleBatchDelete() {
	if (selectedIds.value.length === 0) {
		uni.showToast({ title: '请先选择要删除的项', icon: 'none' })
		return
	}
	const confirmed = await showConfirm('确认删除', `确定要删除选中的 ${selectedIds.value.length} 项吗？`)
	if (!confirmed) return
	try {
		const dhPatients = uniCloud.importObject('dh-patients')
		const result = await dhPatients.batchDeletePatients(selectedIds.value, '批量删除')
		if (result.code === 200) {
			uni.showToast({ title: '删除成功', icon: 'success' })
			selectedIds.value = []
			loadData()
		} else {
			uni.showToast({ title: result.message || '删除失败', icon: 'error' })
		}
	} catch (error) {
		console.error('删除失败:', error)
		uni.showToast({ title: '删除失败', icon: 'error' })
	}
}

function handleAdd() { uni.navigateTo({ url: '/pages/business/patients/add' }) }
function handleView(id) { uni.navigateTo({ url: `/pages/business/patients/detail?id=${id}` }) }
function handleEdit(id) { uni.navigateTo({ url: `/pages/business/patients/edit?id=${id}` }) }
async function handleDelete(id) {
	const confirmed = await showConfirm('确认删除', '确定要删除此患者档案吗？删除后无法恢复。')
	if (!confirmed) return
	try {
		const dhPatients = uniCloud.importObject('dh-patients')
		const result = await dhPatients.deletePatient(id)
		if (result.code === 200) { uni.showToast({ title: '删除成功', icon: 'success' }); loadData() } else { uni.showToast({ title: result.message || '删除失败', icon: 'error' }) }
	} catch (error) { console.error('删除失败:', error); uni.showToast({ title: '删除失败', icon: 'error' }) }
}
function handlePreviousPage() { if (currentPage.value > 1) { currentPage.value--; loadData() } }
function handleNextPage() { if (currentPage.value < totalPages.value) { currentPage.value++; loadData() } }
function handlePageSizeChange(e) { const index = e.detail.value; pageSize.value = pageSizeValues[index]; currentPage.value = 1; loadData() }
function showConfirm(title, content) { return new Promise((resolve) => { uni.showModal({ title, content, confirmText: '确定', cancelText: '取消', success: (res) => { resolve(res.confirm) } }) }) }
</script>
<style scoped lang="scss">
.page-container { padding: 20px; background-color: #f5f7fa; min-height: 100vh; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); }
.header-left { display: flex; flex-direction: column; }
.page-title { font-size: 20px; font-weight: 600; color: #1f2937; margin-bottom: 4px; }
.page-subtitle { font-size: 12px; color: #6b7280; }
.header-right { display: flex; gap: 10px; }
.btn { padding: 6px 14px; border-radius: 6px; border: none; cursor: pointer; font-size: 14px; font-weight: 500; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 6px; height: 34px; box-sizing: border-box; &:disabled { opacity: 0.5; cursor: not-allowed; } &.btn-primary { background-color: #3b82f6; color: white; &:active { background-color: #2563eb; } } &.btn-default { background-color: #e5e7eb; color: #374151; &:active { background-color: #d1d5db; } } &.btn-small { padding: 6px 12px; font-size: 12px; } }
.icon { font-size: 16px; }
.filter-section { display: flex; flex-direction: column; gap: 16px; margin-bottom: 20px; }
.batch-actions { display: flex; align-items: center; gap: 12px; background: #eff6ff; border: 1px solid #dbeafe; padding: 12px; border-radius: 8px; }
.batch-count { font-size: 14px; color: #1e40af; font-weight: 500; }
.checkbox-cell { display: flex; justify-content: center; align-items: center; }
.search-box { display: flex; gap: 8px; background: white; padding: 12px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); }
.search-input { flex: 1; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; height: 38px; box-sizing: border-box; &:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1); } }
.btn-search { padding: 8px 16px; background-color: #3b82f6; color: white; border: 1px solid #3b82f6; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; height: 38px; box-sizing: border-box; display: flex; align-items: center; &:active { background-color: #2563eb; } }
.btn-reset { padding: 8px 16px; background-color: #e5e7eb; color: #374151; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; height: 38px; box-sizing: border-box; display: flex; align-items: center; &:active { background-color: #d1d5db; } }
.table-wrapper { background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); margin-bottom: 20px; }
.loading-state, .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 60px 20px; }
.loading-text { font-size: 14px; color: #6b7280; }
.empty-icon { font-size: 48px; margin-bottom: 12px; }
.empty-text { font-size: 14px; color: #6b7280; margin-bottom: 16px; }
.table-container { overflow-x: auto; max-width: 100%; 
	&::-webkit-scrollbar { height: 8px; }
	&::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; }
	&::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; 
		&:hover { background: #94a3b8; }
	}
}
.table-header { display: grid; grid-template-columns: 60px 100px 60px 70px 120px 80px 100px 120px 140px 140px 140px; gap: 12px; padding: 12px 16px; background-color: #f9fafb; border-bottom: 1px solid #e5e7eb; font-size: 12px; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; min-width: 1200px; .table-cell { justify-content: center; } }
.table-row { display: grid; grid-template-columns: 60px 100px 60px 70px 120px 80px 100px 120px 140px 140px 140px; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #e5e7eb; align-items: center; transition: background-color 0.2s ease; min-width: 1200px; &:hover { background-color: #f9fafb; } &:last-child { border-bottom: none; } .table-cell { justify-content: center; } .col-actions { justify-content: flex-end; } }
.table-cell { display: flex; align-items: center; }
.cell-text { font-size: 14px; color: #1f2937; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; 
	&.text-truncate { max-width: 100%; }
}
.col-actions { display: flex; gap: 6px; justify-content: flex-end; }
.clickable { cursor: pointer; transition: background-color 0.2s ease; &:hover { background-color: #f9fafb; } }
.action-btn { padding: 4px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: 500; transition: all 0.3s ease; white-space: nowrap; height: 26px; display: flex; align-items: center; box-sizing: border-box; &.edit-btn { background-color: #fef3c7; color: #92400e; &:hover { background-color: #fde68a; } &:active { background-color: #fcd34d; } } &.delete-btn { background-color: #fee2e2; color: #991b1b; &:hover { background-color: #fecaca; } &:active { background-color: #fca5a5; } } }
.pagination-section { display: flex; justify-content: space-between; align-items: center; background: white; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); }
.pagination-info { display: flex; align-items: center; gap: 16px; font-size: 12px; color: #6b7280; }
.page-size-selector { display: flex; align-items: center; gap: 8px; }
.selector-label { font-size: 12px; color: #6b7280; }
.selector-picker { flex-shrink: 0; }
.selector-input { padding: 4px 8px; border: 1px solid #d1d5db; border-radius: 4px; font-size: 12px; color: #374151; background-color: white; cursor: pointer; min-width: 70px; text-align: center; }
.pagination-controls { display: flex; gap: 8px; }
@media (max-width: 768px) {
	.page-container { padding: 12px; }
	.page-header { flex-direction: row; align-items: center; gap: 8px; padding: 12px; }
	.header-left { flex: 1; min-width: 0; }
	.header-right { flex-shrink: 0; }
	.page-title { font-size: 16px; }
	.page-subtitle { font-size: 11px; }
	.btn { padding: 6px 12px; font-size: 13px; }
	.search-box { flex-wrap: wrap; }
	.search-input { width: 100%; margin-bottom: 8px; }
	.btn-search, .btn-reset { flex: 1; }
	.table-wrapper { overflow-x: auto; }
	.table-container { min-width: 1200px; overflow-x: auto; }
	.pagination-section { flex-direction: column; gap: 12px; align-items: flex-start; }
	.pagination-info { flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; }
	.pagination-controls { width: 100%; }
}
</style>

